package com.key.oa.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.key.keyleaderoa.R;
import com.key.oa.common.Json;
import com.key.oa.http.HttpUncheck;
import com.key.oa.util.SysParams;
import com.key.oa.util.UncheckedData;
import com.key.oa.util.Util;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends ListActivity {
	
	public List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	public ProgressDialog pDialog = null;
	public NotificationManager manager = null;
	
	private ListViewAdapter adapter = null;
	private ListView listView = null;
	private Button loadMoreButton = null;
	private View loadMoreView = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.key_main_menu);
		
		if( SysParams.mainActivity != null ) {
			SysParams.mainActivity.finish();
		}
		SysParams.mainActivity = this;
		
		if( manager != null ) {
			manager.cancel(0);
		}
		
		clear();
		getHttpData();
		
		adapter = new ListViewAdapter(this, list);
		loadMoreView = getLayoutInflater().inflate(R.layout.load_more, null,false);
		loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadMoreButton);
		listView = getListView();

		listView.addFooterView(loadMoreView);
		setListAdapter(adapter);
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				
				arg0.setBackgroundDrawable(getResources().getDrawable(R.drawable.choice));
				
				Intent shareContentIntent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putString("pos", Integer.toString(arg2)); 
				shareContentIntent.setClass(MainActivity.this,UncheckedActivity.class);
				shareContentIntent.putExtras(bundle);
				startActivity(shareContentIntent);
			}
		});
	}

	private void getHttpData() {
		
		pDialog = new ProgressDialog(MainActivity.this);
		pDialog.setTitle("提示");
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pDialog.setMessage("正在加载...请稍后...");
		pDialog.setIndeterminate(true);
		pDialog.show();
		
		HttpSend();
	}
	
	private void HttpSend() {
		
		new Thread(new Runnable() {
			public void run() {
				try {
					String uri = Util.serverdata.getUriUnchecked();
					String result = HttpUncheck.get(uri);
					if( result == null || result.length() == 0 ) {
						return;
					}
					
					List< Map<String,String> > parseResult = Json.parse(result);
					if( parseResult == null ) {
						throw new Exception("Parse the data error.");
					}
					
					int size = 0;
					for( Map<String,String> map : parseResult ) {
						
						UncheckedData ud = new UncheckedData();
						ud.saveUnckecked(map);
						
						int sign = 0;
						for( UncheckedData data : Util.uncheckdata ) {
							if( ud.getUnchecked("Id").equals(data.getUnchecked("Id")) ) {
								sign = 1;
								break;
							}
						}
						if( sign == 1 ) {
							continue;
						}
						
						size ++;
						Util.uncheckdata.add(ud);
						
						Map<String,Object> mapSO = new HashMap<String,Object>();
						mapSO.put("cost_budget", map.get("cost_budget"));
						mapSO.put("StartTime", map.get("StartTime"));
						mapSO.put("Classfication", map.get("Classfication"));
						mapSO.put("depname", map.get("depname"));
						mapSO.put("name", map.get("name"));
						
						list.add(mapSO);
					}
					
					Message m = new Message();
					m.what = size;
					handler.sendMessage(m);
				
				} catch (Exception e) {
					e.printStackTrace();
					Log.e("oa", "error", e);
					Message m = new Message();
					m.what = -1;
					handler.sendMessage(m);
					return;
				} finally {
					if (pDialog != null) {
						pDialog.cancel();
					}
				}
			}
		}).start();
	}

	/**
	 * 点击按钮事件
	 * @param view
	 */
	public void loadMore(View view) {
		loadMoreButton.setText("加载...");
		handler.postDelayed(new Runnable() {
			public void run() {
				getHttpData();
				adapter.notifyDataSetChanged();
				loadMoreButton.setText("点击加载更多");
			}
		}, 2000);
	}

	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case -1:
				Toast.makeText(MainActivity.this, "获取异常", Toast.LENGTH_SHORT).show();
				break;
			default:
				adapter.notifyDataSetChanged();
				Toast.makeText(MainActivity.this, "获取正常,条目:" + msg.what,Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	
	private void addNotificaction() {  
        
		manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);  
        Notification notification = new Notification();
        notification.icon = R.drawable.ic_launcher;
        notification.tickerText = "APM系统通知";
        notification.defaults = Notification.DEFAULT_SOUND;  
        notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;  
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        notification.setLatestEventInfo(this, "内容提示:", "未处理的流程申请数量: "+Integer.toString(list.size())+" 条", pendingIntent);  
        manager.notify(0, notification); 
    }
	
	private void clear() {
		this.list.clear();
		if(adapter != null) {
			this.adapter.list.clear();
		}
		Util.uncheckdata.clear();
	}

	@Override
	public boolean onKeyDown(int kCode, KeyEvent kEvent) {

		if (kCode == KeyEvent.KEYCODE_BACK) {
			SysParams.intentMain = new Intent();  
            SysParams.intentMain.setClass(MainActivity.this, BackgroundService.class);  
            startService(SysParams.intentMain);
            
			Intent intent = new Intent(Intent.ACTION_MAIN);  
			intent.addCategory(Intent.CATEGORY_HOME);  
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
			
			addNotificaction();
			clear();
            return true;
		} else if(kCode == KeyEvent.KEYCODE_HOME) {
			return false;
		} else if(kCode == KeyEvent.KEYCODE_MENU) {
			new AlertDialog.Builder(this)
            .setMessage("退出")    
            .setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {    
                        public void onClick(DialogInterface dialog,int which) {
                        	
                        }    
                    })    
            .setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {    
                        public void onClick(DialogInterface dialog,int whichButton) {
                        	Util.sign = 1;
                        	Intent itent = new Intent();
                            itent.setClass(MainActivity.this, LoginActivity.class);
                            startActivity(itent);
                        }    
                    }).show();    

			return true;  
		}
		return super.onKeyDown(kCode, kEvent);
	}
}
